from django.http import JsonResponse, HttpResponse
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.views.decorators.csrf import csrf_exempt
from web.form.wiki import wikiForm
from django.urls import reverse
from django.shortcuts import render,redirect
from utils.tencent.cos import upload_bucket
from web import models
from utils.encrypt import uid

def wiki(request,project_id):
        """wiki首页"""
        wiki_id = request.GET.get("wiki_id")
        if wiki_id:
             wiki_obj = models.Wiki.objects.filter(id=wiki_id).first()
             return render(request,"wiki.html",{"wiki_obj":wiki_obj})
        return render(request,'wiki.html')


def add(request,project_id):
    """wiki添加"""
    if request.method =="GET":
        form = wikiForm(request)
        return render(request, 'wiki_form.html', {"form":form})
    form = wikiForm(request,data=request.POST)
    if form.is_valid():
         # 对深度进行处理，加深度是为了先展示父级目录
        if form.instance.parent:
            form.instance.depth =  form.instance.parent.depth +1
        else:
            form.instance.depth =1
        form.instance.project = request.manage
        form.save()
        url = reverse('wiki',kwargs={"project_id":request.manage.id})
        return redirect(url)
    return render(request, 'wiki_form.html', {"form": form})


def catalog(request,project_id):
    # 返回数据
    data_list = models.Wiki.objects.filter(project=request.manage).values("id","title","parent_id").order_by("depth","id")
    return JsonResponse({"status":True,"data":list(data_list)})


def delete(request,project_id,wiki_id):
    """删除文章"""
    models.Wiki.objects.filter(project_id=project_id,id=wiki_id).delete()
    url = reverse('wiki', kwargs={"project_id": request.manage.id})
    return redirect(url)


def edit(request,project_id,wiki_id):
    """编辑文章"""
    wiki_obj = models.Wiki.objects.filter(id=wiki_id).first()
    if request.method == "GET":
        form = wikiForm(request,instance=wiki_obj)
        return render(request, "wiki_form.html", {"form":form})
    form = wikiForm(request,instance=wiki_obj,data=request.POST)
    if form.is_valid():
        form.instance.project = request.manage
        # 对深度进行处理，加深度是为了先展示父级目录
        if form.instance.parent:
            form.instance.depth =  form.instance.parent.depth +1
        else:
            form.instance.depth =1
        form.save()
        url = reverse('wiki',kwargs={"project_id":request.manage.id})
        return redirect(url)
    return render(request, "wiki_form.html", {"form": form})

@csrf_exempt
@xframe_options_sameorigin
def upload(request,project_id):
    """ 上传图片 """
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    img_obj = request.FILES.get('editormd-image-file')
    if not img_obj:
        result['message'] ="文件不存在"
        return JsonResponse(result)
    ext = img_obj.name.rsplit('.')[-1] # 取出文件名后缀
    bucket = request.manage.bucket
    file_name = '{}.{}'.format(uid(request.transaction.user.mobile_phone),ext) # 存放文件的名字
    img_url = upload_bucket(Body=img_obj, bucket=bucket, Key=file_name)
    result["success"] =1
    result["url"] = img_url
    print(result)
    return JsonResponse(result)